package com.example.jasypt;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;

/**
 * @author MI
 */ //@MapperScan({"com.learn.*.*.mapper"})
@SpringBootApplication
//@Import(LearnMyBatisAutoConfiguration.class) // 把这个配置类也交给Spring boot源码进行管理
public class SpringBootJasyptApplication implements CommandLineRunner {

    @Autowired
    private ApplicationContext applicationContext;

    @Resource
    private StringEncryptor stringEncryptor;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootJasyptApplication.class, args);
    }


    @Override
    public void run(String... args) throws Exception {

        Environment environment = applicationContext.getBean(Environment.class);

        // 首先获取配置文件里的原始明文信息/首先获取配置文件里的配置项
        String mysqlOriginPswd = environment.getProperty("spring.datasource.password");
        // 首先获取配置文件里的配置项
        String redisOriginPswd = environment.getProperty("spring.redis.password");
        // 加密
        String mysqlEncryptedPswd = encrypt( mysqlOriginPswd );
        String redisEncryptedPswd = encrypt( redisOriginPswd );
//        String aliSmsEncryptedAk = encrypt( aliSmsOriginAk );

        // 打印加密前后的结果对比
        System.out.println( "MySQL原始明文密码为：" + mysqlOriginPswd );
        System.out.println( "Redis原始明文密码为：" + redisOriginPswd );

        System.out.println( "====================================" );
        System.out.println( "MySQL原始明文密码加密后的结果为：" + mysqlEncryptedPswd );
        System.out.println( "Redis原始明文密码加密后的结果为：" + redisEncryptedPswd );
//        System.out.println( "阿里云SMS原始AccessKey密码加密后的结果为：" + aliSmsEncryptedAk );

//        String aliSmsOriginAk = environment.getProperty("ali.sms.access_key_secret");

        // 打印解密后的结果
        System.out.println( "MySQL原始明文解密后密码为：" + mysqlOriginPswd );
        System.out.println( "Redis原始明文解密后密码为：" + redisOriginPswd );
//        System.out.println( "阿里云SMS原始AccessKey密码为：" + aliSmsOriginAk );
    }

    /**
     * Jasyp加密
     * @param originPassWord
     * @return
     */
    private String encrypt( String originPassWord ) {
        String encryptStr = stringEncryptor.encrypt( originPassWord );
        return encryptStr;
    }

    private String decrypt( String encryptedPassword ) {
        String decryptStr = stringEncryptor.decrypt( encryptedPassword );
        return decryptStr;
    }
}
